package top.psjj.news.web;

import top.psjj.news.po.TAdmin;
import top.psjj.news.service.AdminService;
import top.psjj.news.service.impl.AdminServiceImpl;
import top.psjj.news.utils.ServiceProxyFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Auther:小陈的Java
 */
/**
 * 管理员模块
 */
@WebServlet("/admin")
public class AdminServlet extends BasicServlet{
    private AdminService adminService = (AdminService)ServiceProxyFactory.getService(AdminServiceImpl.class);
    private String basicUrl = "/WEB-INF/jsp/";
    //登录页面访问路径 http://127.0.0.1:80/news/admin?method=loginUI
    public void loginUI(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        req.getRequestDispatcher(basicUrl+"login.jsp").forward(req,resp);
    }
    //处理登录业务的方法
    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //获得用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        //根据用户名和密码判断登录是否成功
        TAdmin tAdmin = adminService.login(username,password);
        if(tAdmin==null){
            //登录失败,将错信息转发到页面
            req.setAttribute("error","用户名或密码错误");
            req.getRequestDispatcher(basicUrl+"login.jsp").forward(req,resp);
        } else {
            //登录成功,将信息存入session中
            session.setAttribute("currentAdmin",tAdmin);
            // 重定向
            resp.sendRedirect(req.getContextPath()+"/main?method=mainUI");
        }
    }
    public void logout(HttpServletRequest req,HttpServletResponse resp) throws Exception{
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath()+"/admin?method=loginUI");

    }
}
